package com.jrx.anytxn.param.service.rights.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.PrRightsAndInterestsRes;
import com.jrx.anytxn.param.dto.rights.PrRightsQualificationReq;
import com.jrx.anytxn.param.dto.rights.PrRightsQualificationRes;
import com.jrx.anytxn.param.entity.PrRightsQualification;
import com.jrx.anytxn.param.enums.EnableTagEnum;
import com.jrx.anytxn.param.mapper.ext.ExtPrRightsQualificationMapper;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import com.jrx.anytxn.param.service.rights.IPrRightsQualificationService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName PrRightsQualificationServiceImpl
 *
 * @author lujianyou
 * @version 1.0
 * @description 权益资格参数
 * @date 2021/6/11 11:35
 **/
@Service
public class PrRightsQualificationServiceImpl implements IPrRightsQualificationService {
    private static final Logger logger = LoggerFactory.getLogger(PrRightsQualificationServiceImpl.class);

    @Autowired
    private ISegmentService segmentService;

    @Autowired
    private ExtPrRightsQualificationMapper extPrRightsQualificationMapper;

    @Autowired
    private IPrRightsAndInterestsService prRightsAndInterestsService;

    /**
     * 根据 租户号、权益资格id 获取权益资格参数表
     *
     * @param tenantId
     * @param qualificationId
     * @return
     */
    @Override
    public PrRightsQualification getByTenantIdAndQualificationId(String tenantId, String qualificationId) {
        return extPrRightsQualificationMapper.selectByTenantIdAndRightsQualificationId(tenantId, qualificationId);
    }

    @Override
    public PrRightsQualificationRes getResByTenantIdAndQualificationId(String tenantId, String qualificationId) throws TxnBizException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(qualificationId)) {
            logger.error("商户ID或权益资格ID为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        PrRightsQualification prRightsQualification = extPrRightsQualificationMapper.selectByQualificationId(tenantId,qualificationId);
        if (null == prRightsQualification) {
            logger.error("未查到权益资格参数信息");
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        return BeanMapping.copy(prRightsQualification, PrRightsQualificationRes.class);
    }

    @Override
    public List<PrRightsQualification> listByTenantId(String tenantId) {
        return extPrRightsQualificationMapper.listByTenantId(tenantId);
    }

    /**
     * 根据 租户号、权益资格id 获取权益资格详情
     *
     * @param tenantId
     * @param qualificationId
     * @return
     */
    @Override
    public PrRightsQualificationRes getDetailByTenantIdAndQuaId(String tenantId, String qualificationId) {
        PrRightsQualificationRes res = new PrRightsQualificationRes();
        PrRightsQualification prRightsQualification = getByTenantIdAndQualificationId(tenantId, qualificationId);
        if (prRightsQualification != null) {
            BeanUtils.copyProperties(prRightsQualification, res);
            String rightsIds = prRightsQualification.getRightsIds();
            if (StringUtils.isNotBlank(rightsIds)) {
                List<String> rightsIdArray = Arrays.asList(rightsIds.split(","));
                // 获取当前租户下所有权益列表
                List<PrRightsAndInterestsRes> prRightsAndInterestsList =
                    prRightsAndInterestsService.findAllByTenId(tenantId);
                res.setQualificationCandidateRights(prRightsAndInterestsList.stream()
                    .filter(item -> rightsIdArray.contains(item.getRightsId())).collect(Collectors.toList()));
            }
        }
        return res;
    }

    /**
     * 校验 权益资格参数对象
     *
     * @param tenantId
     * @param qualificationId
     * @param productCode
     * @return
     */
    @Override
    public List<PrRightsQualificationRes> checkQualification(String tenantId, String qualificationId, String productCode) throws TxnBizException{
        List<PrRightsQualification> prRightsQuaToGrantList = new ArrayList<>(8);
        String[] quaIdArray = qualificationId.split(",");
        List<PrRightsQualification> prRightsQualificationList = listByTenantId(tenantId);
        for (int i = 0; i < quaIdArray.length; i++) {
            String quaId  = quaIdArray[i];
            PrRightsQualification rightsQualification = prRightsQualificationList.stream().filter(item -> quaId.equals(item.getQualificationId())).findFirst().orElse(null);
            if (rightsQualification == null) {
                logger.info("根据租户号:{}、权益资格id:{} 查询权益资格参数表，查无记录", tenantId, qualificationId);
                throw new TxnBizException(TxnRespCode.NO_DATA);
            }
            if (!EnableTagEnum.ENABLE.getCode().equals(rightsQualification.getEnableTag())) {
                logger.info("权益资格: {}未启用", rightsQualification.getName());
                throw new TxnBizException(TxnRespCode.RIGHTS_QUALIFICATION_NOT_ENABLE);
            }
            if (!rightsQualification.getAllowProducts().contains(productCode)) {
                logger.info("请求产品编号:{} 与权益资格id:{} 适用产品不匹配", productCode, qualificationId);
                throw new TxnBizException(TxnRespCode.PRODUCT_CODE_AND_QUALIFICATION_ID_MISMATCH);
            }
            prRightsQuaToGrantList.add(rightsQualification);
        }

        List<PrRightsQualificationRes> result = new ArrayList<>(8);
        com.jrx.anytxn.common.uitl.BeanUtils.copyList(prRightsQuaToGrantList,result,PrRightsQualificationRes.class);
        return result;
    }

    @Override
    public Integer addPrRightsQualification(PrRightsQualificationReq prRightsQualificationReq) throws TxnBizException {
        Integer res = 0;
        PrRightsQualification prRightsQualification = BeanMapping.copy(prRightsQualificationReq,PrRightsQualification.class);

        try {
            prRightsQualification.setQualificationId(String.valueOf(System.currentTimeMillis() + segmentService.getId(Constant.PR_RIGHTS_QUALIFICATION_ID)));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        prRightsQualification.setCreateTime(new Date());
        prRightsQualification.setCreateBy(new Date());
        prRightsQualification.setUpdateTime(new Date());
        try {
            prRightsQualification.setId(segmentService.getId(Constant.PR_RIGHTS_QUALIFICATION_ID));
        }catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnBizException(ErrorMsgConstant.ERROR_ID);
        }
        prRightsQualification.setRecordVersionNumber(Constant.VERSION_NUMBER);
        return res = extPrRightsQualificationMapper.insertSelective(prRightsQualification);
    }

    @Override
    public TxnPage<PrRightsQualificationRes> findAllPageByTenantId(Integer pageNum, Integer pageSize, String tenantId) throws TxnException {

        Page<PrRightsQualificationRes> page = PageHelper.startPage(pageNum, pageSize, Constant.ORDER_BY_SORT);
        List<PrRightsQualification> tableList = extPrRightsQualificationMapper.selectByTenId(tenantId);
        if (CollectionUtils.isEmpty(tableList)) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }

        List<PrRightsQualificationRes> res = BeanMapping.copyList(tableList, PrRightsQualificationRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public Integer modifyPrRightsQualification(PrRightsQualificationReq prRightsQualificationReq) throws TxnBizException{
        Integer res = 0;
        PrRightsQualification table = extPrRightsQualificationMapper.selectByTenantIdAndRightsQualificationId(prRightsQualificationReq.getTenantId(),
                prRightsQualificationReq.getQualificationId());
        if (table == null) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnBizException(TxnRespCode.NO_DATA.getMsg());
        }
        PrRightsQualification prShareProfitTable = BeanMapping.copy(prRightsQualificationReq, PrRightsQualification.class);
        // 更新
        return res = extPrRightsQualificationMapper.updateByTenantIdAndQualificationId(prShareProfitTable);
    }

    @Override
    public Boolean removeByTenIdAndQualificationId(String tenantId, String qualificationId) throws TxnBizException {
        if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(qualificationId)) {
            logger.error("租户id或权益权益资格id不可为空");
            throw new TxnBizException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        int i = extPrRightsQualificationMapper.deleteByTenantAndQualificationId(tenantId,qualificationId);
        return i > 0;
    }

    @Override
    public List<PrRightsQualificationRes> findAllByTenId(String tenantId) {
        List<PrRightsQualification> list = extPrRightsQualificationMapper.selectByTenIdAndStatus(tenantId);
        return BeanMapping.copyList(list, PrRightsQualificationRes.class);
    }



}
